<!--添加文章-->
<template>
  <div class="add">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" class="add-ruleForm">
      <el-form-item label="类别" prop="name">
        <el-col>
          <el-input v-model="type.name" placeholder="请输入类别" style="width:200px" readonly></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select v-model="ruleForm.category" placeholder="请选择活动区域" style="width:200px">
          <el-option-group
            v-for="item in category"
            :key="item.id"
            :label="item.name">
            <el-option
              v-for="subItem in item.children"
              :key="subItem.id"
              :label="subItem.name"
              :value="subItem.id">
            </el-option>
          </el-option-group>
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title" placeholder="请输入标题！">
        <el-input v-model="ruleForm.title"></el-input>
      </el-form-item>
      <el-form-item label="摘要" prop="summary" placeholder="请输入摘要！">
        <el-input type="textarea" v-model="ruleForm.summary"></el-input>
      </el-form-item>
      <el-form-item label="视频链接" prop="externalUrl" placeholder="请输入视频链接">
        <el-input v-model="ruleForm.externalUrl"></el-input>
      </el-form-item>
      <el-form-item label="关键字" prop="tag" placeholder="请输入关键字！">
        <div class="editDiv">
          <span v-for="(key,index) in keyList" :key="index" class="keyword">{{key}}
            <i class="el-icon-close" @click="delkey(index)"></i></span>
          <input v-model="keyValue" @keyup.13="addkey($event)" placeholder="请输入文章关键词，可输入多个"/>
        </div>
      </el-form-item>
      <el-form-item label="计划发布时间" required>
        <el-col style="width:200px">
          <el-form-item prop="schedulePublishTime">
            <el-date-picker type="datetime" format="yyyy-MM-dd hh:mm" value-format="yyyy-MM-dd hh:mm"
                            placeholder="请选择日期" v-model="ruleForm.schedulePublishTime"
                            style="width: 100%;" :change="handleDataChange"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="缩略图" prop="thumbnailFileId" placeholder="请输入关键字！">
        <el-upload
          class="upload-demo"
          name="file"
          action="/api/file/upload?module=public"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :file-list="fileList"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <textarea name="editor" id="editor" rows="10" cols="80" placeholder="请输入。。。">
        </textarea>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm','add')">保存</el-button>
        <el-button type="primary" @click="submitForm('ruleForm','add-publish')">保存并发布</el-button>
        <!--<el-button @click="resetForm('ruleForm')">重置</el-button>-->
        <el-button @click="cancel()">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import { mapGetters, mapActions } from 'vuex'

  export default {
    name: 'AddArticle',
    data () {
      var validateData = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入计划发布时间!'))
        } else {
          let date = new Date(value)
          let now = Date.now()
          if (date <= now) {
            callback(new Error('您选择的时间小于当前时间!'))
          }
          callback()
        }
      }
      return {
        fileList: [],//上传图片列表
        keyList: [], //关键字列表
        content: null, //ckEditor内容
        keyValue: '',//关键字输入之后清空
        ruleForm: {
          type: '', //类别
          category: null,//分类
          title: '', //标题
          summary: '', //摘要
          schedulePublishTime: '', //计划发布时间
          thumbnailFileId: '', //缩略图id
          externalUrl: ''//视频链接
        },
        rules: {
          category: [
            {required: true, message: '请选择分类', trigger: 'change'}
          ],
          title: [
            {required: true, message: '请输入标题', trigger: 'blur'}
          ],
          summary: [
            {min: 0, max: 255, message: '不能超过255个字', trigger: 'blur'}
          ],
          schedulePublishTime: [
            {validator: validateData, trigger: 'change'}
          ],
        }
      }
    },
    created () {
      this.ruleForm.category = this.categoryID
    },
    mounted () {
      CKEDITOR.replace('editor', {height: '300px', width: '100%', toolbar: 'Full'})
    },
    components: {},
    computed: {
      ...mapGetters([
        'category',
        'type',
        'categoryID'
      ])
    },
    methods: {
      ...mapActions([
        'setCategory',
        'setType',
        'setCategoryID'
      ]),
      submitForm (formName, method) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            if (this.ruleForm.thumbnailFileId === '') {
              this.$message.error('缩略图还未上传')
              return false
            }
            if (CKEDITOR.instances.editor.getData() === '' && this.ruleForm.externalUrl === '') {
              this.$message.error('视频和内容必须输入一项!')
              return false
            }
            let params = {
              type: this.type.enName,
              category: this.ruleForm.category,
              schedulePublishTime: this.ruleForm.schedulePublishTime,
              summary: this.ruleForm.summary,
              tags: this.keyList,
              title: this.ruleForm.title,
              thumbnailFileId: this.ruleForm.thumbnailFileId,
              vedioInfo: {
                externalUrl: this.ruleForm.externalUrl,
              },
              content: CKEDITOR.instances.editor.getData()
            }
            let res = await this.axios.post(`/api/admin/article/${method}`, params)
            if (res.data.state === 0) {
              this.$message('添加成功!')
              this.$router.push({path: `/college`})
            } else {
              this.$message.error(res.data.errorMessage)
            }
          }
        })
      },
      resetForm (formName) {
        this.$refs[formName].resetFields()
      },
      cancel () {
        this.$router.go(-1)
      },
      handleRemove (file, fileList) {
        console.log(file, fileList)
      },
      handleSuccess (response, file, fileList) {
        this.ruleForm.thumbnailFileId = response.bizData.id
      },
      handlePreview (file) {
        console.log(file)
      },
//      onEditorBlur () {//失去焦点事件
//      },
//      onEditorFocus () {//获得焦点事件
//      },
//      onEditorChange () {//内容改变事件
//      }
      addkey (e) {
        if (this.keyList.indexOf(e.target.value) === -1) {
          this.keyList.push(e.target.value)
        }
        this.keyValue = ''
      },
      delkey (index) {
        this.keyList.splice(index, 1)
      },
      handleDataChange () {

      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="stylus" type="text/stylus">
  .add
    display flex
    width 100%
    background #fff
    height 100%
    overflow-y auto

  .add-ruleForm
    padding 30px 0
    width 60%

  .editDiv
    height 40px
    line-height 40px
    border 1px solid #dcdfe6
    border-radius 4px
    input
      position absolute
      top 1px
      border none
      outline none
      line-height 36px
      margin-top 2px
      padding 0 15px
      width 80%

  .keyword
    text-align center
    padding 3px 5px
    margin-left 5px
    border-radius 3px
    background #ccc
    > i
      margin-left 3px

</style>
